import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

Vue.config.productionTip = false

Vue.prototype.axios = axios

// axios前置拦截器
axios.interceptors.request.use(config=>{
  //在所有请求中加入认证token
  let token = window.sessionStorage.getItem('token')
  if(token != null){
    config.headers['Authorization'] = token
  }
  return config
},error=>{
  Promise.reject(error)
})

//axios后置拦截器
axios.interceptors.response.use(response=>{
  //当token快过期时，后台会进行延期处理，生成新的token，前台需更换新的token
  let refToken = response.headers['x-token']
  if(refToken){
    //如果有新的token，则替换原有token
    window.sessionStorage.setItem('token',refToken);
  }
  console.log("后置拦截",response)
  return response
},error=>{
  console.log('后置拦截错误',error.response.data)
  //统一处理服务端的报错
  if(error.response){
    alert(error.response.data.msg);
  }
  return Promise.reject(error);
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
